package com.sskj.lightning.ui.activity;

import android.arch.lifecycle.Observer;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.widget.FrameLayout;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.gyf.barlibrary.ImmersionBar;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpHeaders;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.LanguageUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.SPConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.AppVersionBean;
import com.sskj.lib.bean.GonggaoBean;
import com.sskj.lib.bean.MainTabChange;
import com.sskj.lib.bean.TabItem;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.box.LiveDataBus;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.ui.fragment.AppUpDateFragment;
import com.sskj.lib.util.APKVersionCodeUtils;
import com.sskj.lib.util.CommonUtil;
import com.sskj.lib.util.TipUtil;
import com.sskj.lightning.R;
import com.sskj.lightning.component.DaggerUserDataComponent;
import com.sskj.lightning.presenter.MainActivityPresenter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import sskj.lee.appupdatelibrary.BaseUpdateDialogFragment;
import sskj.lee.appupdatelibrary.BaseVersion;

@Route(path = RConfig.APP_MAIN)
public class MainActivity extends BaseActivity<MainActivityPresenter> {
    @BindView(R.id.commonTabLayout)
    CommonTabLayout commonTabLayout;
    @BindView(R.id.frameLayout)
    FrameLayout frameLayout;
    @Inject
    UserViewModel userViewModel;
    private UserData userData;
    private int curPos = 0;
    private ArrayList<Fragment> fragments;
    HashMap<Integer, Fragment> tabMap = new HashMap<>();
    private MaterialDialog gongGaoTip;

    @Override
    protected int getLayoutId() {
        ImmersionBar.with(this).statusBarColor(R.color.libTextWhite).statusBarDarkFont(true).init();

        return R.layout.app_activity_main;
    }

    @Override
    public boolean getImmersion() {
        return false;
    }

    @Override
    public MainActivityPresenter getPresenter() {
        return new MainActivityPresenter();
    }

    @Override
    protected void dealFirstSaveInstance(Bundle savedInstanceState) {
        FragmentManager mManager = getSupportFragmentManager();
        if (savedInstanceState != null) {
            List<Fragment> fragments = mManager.getFragments();
            FragmentTransaction fragmentTransaction = mManager.beginTransaction();
            for (int i = 0; i < fragments.size(); i++) {
                fragmentTransaction.remove(fragments.get(i));
            }
            fragmentTransaction.commitAllowingStateLoss();
        }
    }


    @Override
    protected void initView() {
        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }

        });


        ArrayList<CustomTabEntity> tabItems = new ArrayList<>();
        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.appmainActivity1), R.mipmap.lib_icon_menu_first_unselect, R.mipmap.lib_icon_menu_first_select));
        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.appmainActivity2), R.mipmap.lib_icon_menu_second_unselect, R.mipmap.lib_icon_menu_second_select));
        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.appmainActivity3), R.mipmap.lib_icon_menu_third_unselect, R.mipmap.lib_icon_menu_third_select));
        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.appmainActivity4), R.mipmap.lib_icon_menu_four_unselect, R.mipmap.lib_icon_menu_four_select));
        tabItems.add(new TabItem(App.INSTANCE.getString(R.string.appmainActivity5), R.mipmap.lib_icon_menu_five_unselect, R.mipmap.lib_icon_menu_five_select));
        commonTabLayout.setTabData(tabItems);
        commonTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                if (position == 3 && userData == null) {
                    showLogin();
                } else {
                    changeTab(position);
                }
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        fragments = new ArrayList<>();
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.HANG_HANGQING).navigation());
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.HANG_FRAGMENT_ZIXUN).navigation());
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.LEVEL_FRAGMENT_MAIN).withString(Constans.CODE, "BTC/USDT").navigation());
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.FABI_FRAGMENT).navigation());
        fragments.add((Fragment) ARouter.getInstance().build(RConfig.MINE_FRAGMENT_MAIN).navigation());

        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.frameLayout, fragments.get(0))
                .add(R.id.frameLayout, fragments.get(1))
                .hide(fragments.get(1))
                .show(fragments.get(0))
                .commitAllowingStateLoss();
        tabMap.put(0, fragments.get(0));
        tabMap.put(1, fragments.get(1));


    }

    private void changeTab(int position) {
        if (tabMap.get(position) == null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.frameLayout, fragments.get(position))
                    .hide(fragments.get(curPos))
                    .show(fragments.get(position))
                    .commitAllowingStateLoss();
            tabMap.put(position, fragments.get(position));
        } else {
            getSupportFragmentManager()
                    .beginTransaction()
                    .hide(fragments.get(curPos))
                    .show(fragments.get(position))
                    .commitAllowingStateLoss();
        }
        RxBus.getDefault().post(new MainTabChange(position));
        curPos = position;
        if (curPos != 4) {
            ImmersionBar.with(this).statusBarColor(com.sskj.lib.R.color.libTextWhite).statusBarDarkFont(true).init();
        } else {
            ImmersionBar.with(this).transparentStatusBar().init();
        }
    }

    @Override
    protected void initData() {
        mPresenter.initWebSocket();
        mPresenter.getNewVersion();
        LiveDataBus.get().with(RxBusCode.SHOW_GONGGAO,Integer.class)
                .observe(this, integer -> showGonggao());
        LiveDataBus.get().with(RxBusCode.CHANGE_MAIN_TAB,Integer.class)
                .observe(this,integer -> {
                    commonTabLayout.setCurrentTab(integer);
                    changeTab(integer);
                });
//        AppVersionBean appVersionBean = new AppVersionBean();
//        appVersionBean.setContent("1231231");
//        appVersionBean.setVersion("1.0.1");
//        appVersionBean.setAddr("http://192.168.1.181/jingbi_1.0.0.apk");
//        appVersionBean.setUptype(1);
//        onVersionDataSuccess(appVersionBean);

    }

    private void showLogin() {
        commonTabLayout.setCurrentTab(curPos);
        ARouter.getInstance().build(RConfig.LOGIN_LOGIN).navigation();
        overridePendingTransition(R.anim.lib_anim_in, R.anim.lib_anim_out);
    }


    public void showGonggao() {
        mPresenter.getGonggao();
    }

    public void showGonggao(GonggaoBean data) {
        if (data==null||TextUtils.isEmpty(data.getDetails())) {
            return;
        }
        if (!TextUtils.isEmpty(data.getDetails().trim())) {
            TipUtil.getSureCancelTip(this, data.getTile(), data.getDetails(), App.INSTANCE.getString(R.string.appmainActivity6), () -> {
            });
        }
    }

    public void onVersionDataSuccess(AppVersionBean versionBean) {
        if (versionBean == null) {
            return;
        }
        String verName = APKVersionCodeUtils.getVerName(this);
        versionBean.setViewStyle(BaseVersion.NOTIFYCATION_STYLE);

        if (APKVersionCodeUtils.compareVersion(versionBean.getAppVersion(), verName) == 1) {
            android.app.FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
            getFragmentManager().beginTransaction();
            AppUpDateFragment appUpDateFragment = new AppUpDateFragment();//自定义UI
            Bundle bundle = new Bundle();
            bundle.putSerializable(BaseUpdateDialogFragment.INTENT_KEY, versionBean);
            appUpDateFragment.setArguments(bundle);
            appUpDateFragment.show(fragmentTransaction, "update");
        }
    }

    @Subscribe(code = RxBusCode.LOGOUT, threadMode = ThreadMode.MAIN)
    public void changeHangQing() {
        commonTabLayout.setCurrentTab(0);
        changeTab(0);
    }

}
